﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Data;
using System.ComponentModel;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for pengguna.xaml
    /// </summary>
    public partial class pengguna : Window
    {
        private string ID = "";
        private bool isUbah = false;
        private DataSet ubah = new DataSet();
        public pengguna()
        {
            InitializeComponent();
            oldpasswordText.Visibility = System.Windows.Visibility.Hidden;
        }

        public pengguna(string ID)
        {
            this.ID = ID;
            isUbah = true;
            InitializeComponent();
            label1.Content = "Ubah Pengguna";
            addButton.Content = "Edit";
            cancelButton.Content = "Cancel";
            label4.Content = "Old Password";
            label5.Content = "New Password";
            usernameText.Visibility = System.Windows.Visibility.Hidden;
            Title = "TAMS UP :: Form :: Ubah Pengguna";
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                try
                {
                    homeWindow.Con.Open();

                    if (!isUbah)
                    {
                        string _Insert = @"insert into pengguna (username,password,nama,role) Values('" + usernameText.Text + "','" +
                            password.EncryptString(confirmText.Password) + "','" + namaText.Text + "','" +
                            roleBox.Text + "');";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);

                        // Execute the command
                        _cmd.ExecuteNonQuery();

                        MessageBox.Show("Berhasil menambahkan pengguna baru", "New User");
                        restart();
                        homeWindow.Con.Close();
                    }
                    else
                    {
                        string _Insert = @"update pengguna
                                    set password = '" + password.EncryptString(confirmText.Password) + "', Nama = '" + namaText.Text + "',  Role = '" + roleBox.Text +
                                                        "' where username = '" + ID + "';";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();
                        homeWindow.Con.Close();
                        MessageBox.Show("Berhasil Mengubah identitas pengguna", "Edit User");
                        homeWindow.top.Focus();
                        homeWindow.top.refresh();
                        this.Close();
                    }
                    homeWindow.top.Focus();
                    homeWindow.top.refresh();
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
        }

        private void restart()
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            roleBox.SelectedIndex = 0;
            roleBox.Background = validColor;
            usernameText.Text = "";
            usernameText.Background = validColor;
            passwordText.Password = "";
            passwordText.Background = validColor;
            confirmText.Password = "";
            confirmText.Background = validColor;
            namaText.Text = "";
            namaText.Background = validColor;
        }

        private Boolean errorChecking()
        {
            Boolean valid = true;
            Brush invalidColor = new SolidColorBrush(Color.FromRgb(255, 225, 0));
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            if (roleBox.SelectedIndex == -1)
            {
                roleBox.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                roleBox.Background = validColor;
            }
            if (!isUbah)
            {
                if (usernameText.Text.Length < 4 || usernameText.Text.Length > 12)
                {
                    usernameText.Background = invalidColor;
                    if (valid) valid = false;
                }
                else
                {
                    usernameText.Background = validColor;
                }
            }
            if (!isUbah)
            {
                try
                {
                    homeWindow.Con.Open();
                    SqlDataAdapter da = new SqlDataAdapter("Select username from pengguna where username = '" + usernameText.Text + "'", homeWindow.Con);
                    DataSet ds = new DataSet();
                    da.Fill(ds, "Pengguna");
                    if (ds.Tables["Pengguna"].Rows.Count > 0)
                    {
                        usernameText.Background = invalidColor;
                        if (valid) valid = false;
                    }
                    homeWindow.Con.Close();
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
            if ((passwordText.Password.Length < 4) || (passwordText.Password.Length > 12))
            {
                passwordText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                passwordText.Background = validColor;
            }
            if (!confirmText.Password.Equals(passwordText.Password))
            {
                confirmText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                confirmText.Background = validColor;
            }
            if (isUbah)
            {
                try
                {
                    homeWindow.Con.Open();
                    SqlDataAdapter da = new SqlDataAdapter("Select password from pengguna where username = '" + ID + "'", homeWindow.Con);
                    DataSet ds = new DataSet();
                    da.Fill(ds, "Pengguna");
                    if (!(ds.Tables["Pengguna"].Rows[0].ItemArray.ElementAt(0).ToString()).Equals(password.EncryptString(oldpasswordText.Password)))
                    {
                        oldpasswordText.Background = invalidColor;
                        if (valid) valid = false;
                    }
                    else if (!passwordText.Password.Equals(confirmText.Password))
                    {
                        passwordText.Background = invalidColor;
                        confirmText.Background = invalidColor;
                        if (valid) valid = false;
                    }
                    else
                    {
                        oldpasswordText.Background = validColor;
                        passwordText.Background = validColor;
                        confirmText.Background = validColor;
                    }
                    homeWindow.Con.Close();
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
            if ((namaText.Text == "") || (namaText.Text.Length > 25))
            {
                namaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                namaText.Background = validColor;
            }
            if (!valid)
            {
                MessageBox.Show("Ada kesalahan pengisian informasi penambahan pengguna\nUsername dan Password harus antara 4 sampai 12 karakter. Nama maksimal 25 karakter.", "Invalid Information");
            }
            return valid;
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                homeWindow.top.Focus();
                homeWindow.top.refresh();
                this.Close();
            }
            else
            {
                restart();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                try
                {
                    homeWindow.Con.Open();

                    SqlDataAdapter da = new SqlDataAdapter("select * from pengguna where username = '" + ID + "';", homeWindow.Con);
                    ubah = new DataSet();
                    da.Fill(ubah, "Daftar Pengguna");
                    usernameText.Text = ubah.Tables["Daftar Pengguna"].Rows[0].ItemArray.ElementAt(0).ToString();
                    namaText.Text = ubah.Tables["Daftar Pengguna"].Rows[0].ItemArray.ElementAt(2).ToString();
                    roleBox.SelectedItem = ubah.Tables["Daftar Pengguna"].Rows[0].ItemArray.ElementAt(3).ToString();
                    usernameText.IsReadOnly = true;
                    homeWindow.Con.Close();
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void pengguna_close(object sender, CancelEventArgs e)
        {
            homeWindow.top.Focus();
            homeWindow.top.refresh();
        }
    }
}
